/* eslint-disable @typescript-eslint/indent */
/* eslint-disable indent */
import React, { useRef, useState } from 'react';

import { Cascader, DatePicker, Form, Input, message, Radio, Select, Typography } from 'antd';
import moment from 'moment';
import PropTypes from 'prop-types';
import { useDeepCompareEffect } from 'react-use';

import CityPicker from '@/components/CityPicker';
import { useRequest } from '@/hooks';
import useDictionary from '@/hooks/useDictionary';

import FormContainer from './FormContainer';

const { Option } = Select;
const { Text } = Typography;

// 户籍类型字典
export const HOUSEHOLD_TYPE_MAP = {
    HouseholdType1_local: [
        {
            code: 'household2',
            value: 'HouseholdType2_town',
            text: '城镇'
        },
        {
            code: 'household2',
            value: 'HouseholdType2_village',
            text: '农村'
        }
    ],
    HouseholdType1_outland: [
        {
            code: 'household2-2',
            value: 'HouseholdType2_town_inner',
            text: '城镇（省内）'
        },
        {
            code: 'household2-2',
            value: 'HouseholdType2_village_inner',
            text: '农村（省内）'
        },
        {
            code: 'household2-2',
            value: 'HouseholdType2_town_outter',
            text: '城镇（省外）'
        },
        {
            code: 'household2-2',
            value: 'HouseholdType2_village_outter',
            text: '农村（省外）'
        }
    ]
};

// 户籍类型选项
export const CENSUS_REGISTER_OPTIONS = [
    {
        value: 'HouseholdType1_local',
        label: '本地',
        children: [
            {
                value: 'HouseholdType2_town',
                label: '城镇'
            },
            {
                value: 'HouseholdType2_village',
                label: '农村'
            }
        ]
    },
    {
        value: 'HouseholdType1_outland',
        label: '外地',
        children: [
            {
                value: 'HouseholdType2_town_inner',
                label: '城镇（省内）'
            },
            {
                value: 'HouseholdType2_village_inner',
                label: '农村（省内）'
            },
            {
                value: 'HouseholdType2_town_outter',
                label: '城镇（省外）'
            },
            {
                value: 'HouseholdType2_village_outter',
                label: '农村（省外）'
            }
        ]
    }
];

/**
 * 员工档案 - 个人信息
 */
const BasicInfoSection = ({ formData, onChange, readonly, saveAction, ...props }) => {
    const formRef = useRef();
    // 提交
    const { run: submitRun } = useRequest(submitData => saveAction && saveAction(submitData), {
        manual: true
    });
    // 字典数据
    const [sexTypeList, getSexTypeText] = useDictionary('sexType');
    const [, getAgreeTypeText] = useDictionary('agreeType');

    // 国籍/户籍预处理
    const restoreArrayLinkString = data => (!data ? [] : data.split(','));
    // 是否显示户籍类型, 只用国籍是中国的才显示
    const [showHousehold, setShowHousehold] = useState(false);
    // 户籍类型
    const [firstHouseholdType, setFirstHouseholdType] = useState(undefined);
    const [secondHouseholdType, setSecondHouseholdType] = useState(undefined);
    const handleOnHouseHoldChange = record => {
        setShowHousehold(record[0] === '中国');
    };

    // mounted
    useDeepCompareEffect(() => {
        // 判断是否显示户籍类型
        handleOnHouseHoldChange(restoreArrayLinkString(formData?.nationalArea));
        setFirstHouseholdType(formData?.firstHouseholdType);
        setSecondHouseholdType(formData?.secondHouseholdType);
    }, [formData]);

    // 保存
    const handleSubmit = async values => {
        const submitData = Object.assign({
            entryPersonnelCode: formData.entryPersonnelCode,
            detailAddress: values.detailAddress,
            birthday: moment(values?.birthday).format('YYYY-MM-DD'),
            employeeName: values.employeeName,
            employeeEnglishName: values.employeeEnglishName,
            highestDegree: values.highestDegree,
            idCard: values.idCard,
            address: values.address.join(','),
            nationalArea: values.nationalArea.join(','),
            sex: values.sex,
            email: values.email,
            joinWorkTime: moment(values.joinWorkTime).format('YYYY-MM'),
            areaCode: values.areaCode,
            mobile: values.mobile
        });
        // 表单值预处理
        if (values?.firstHouseholdType) {
            submitData.firstHouseholdType = values?.firstHouseholdType[0];
            submitData.secondHouseholdType = values?.firstHouseholdType[1];
        }
        // 提交
        const res = await submitRun(submitData);
        if (res.code === 10000) {
            message.success(res.msg);
            onChange(submitData);
        } else {
            message.error(res.msg);
        }
    };

    // render
    return (
        <FormContainer
            ref={formRef}
            title="个人信息"
            hasEditAuth={!readonly && !!saveAction}
            onSubmit={handleSubmit}
            {...props}
        >
            {({ getFieldDecorator }, editStatus) => (
                <>
                    <Form.Item label="中文姓名">
                        {editStatus ? (
                            getFieldDecorator('employeeName', {
                                initialValue: formData?.employeeName || '',
                                rules: [
                                    { required: true, message: '请输入中文名' },
                                    {
                                        validator(rule, value, callback) {
                                            if (
                                                /[`~!#$%^&*()+=<>?:"{}|~！#￥%……&*（）={}|《》？：“”【】、；‘’，。、]/g.test(
                                                    value
                                                )
                                            ) {
                                                callback('不允许输入特殊字符');
                                            } else {
                                                callback();
                                            }
                                        }
                                    },
                                    {
                                        min: 2,
                                        max: 50,
                                        message: '中文姓名字数范围:2到50个字符'
                                    }
                                ]
                            })(<Input placeholder="请输入中文姓名" allowClear maxLength={100} />)
                        ) : (
                            <div className="multiLineText">{formData?.employeeName || '--'}</div>
                        )}
                    </Form.Item>
                    <Form.Item label="英文名">
                        {editStatus ? (
                            getFieldDecorator('employeeEnglishName', {
                                initialValue: formData?.employeeEnglishName || '',
                                rules: [
                                    {
                                        validator(rule, value, callback) {
                                            if (
                                                /[`~!#$%^&*()+=<>?:"{}|~！#￥%……&*（）={}|《》？：“”【】、；‘’，。、]/g.test(
                                                    value
                                                )
                                            ) {
                                                callback('不允许输入特殊字符');
                                            } else {
                                                callback();
                                            }
                                        }
                                    },
                                    {
                                        min: 2,
                                        max: 50,
                                        message: '英文名字数范围:2到50个字符'
                                    }
                                ]
                            })(<Input placeholder="请输入英文名" allowClear maxLength={100} />)
                        ) : (
                            <div className="multiLineText">{formData?.employeeEnglishName || '--'}</div>
                        )}
                    </Form.Item>
                    <Form.Item label="性别">
                        {editStatus ? (
                            getFieldDecorator('sex', {
                                initialValue: formData?.sex || undefined,
                                rules: [
                                    {
                                        required: true,
                                        message: '性别不能为空'
                                    }
                                ]
                            })(
                                <Radio.Group style={{ marginBottom: 0 }}>
                                    {sexTypeList?.map(item => (
                                        <Radio value={item.value} key={item.value}>
                                            {item.text}
                                        </Radio>
                                    ))}
                                </Radio.Group>
                            )
                        ) : (
                            <Text>{getSexTypeText(formData?.sex) || '--'}</Text>
                        )}
                    </Form.Item>
                    <Form.Item label="证件号码">
                        {editStatus ? (
                            getFieldDecorator('idCard', {
                                initialValue: formData?.idCard || undefined,
                                rules: [
                                    { required: true, message: '证件号码不能为空' },
                                    {
                                        validator(rule, value, callback) {
                                            const regex = /(^\d{8}(0\d|10|11|12)([0-2]\d|30|31)\d{3}$)|(^\d{6}(18|19|20)\d{2}(0[1-9]|10|11|12)([0-2]\d|30|31)\d{3}(\d|X|x)$)/;
                                            if (!regex.test(value)) {
                                                callback('请输入有效的证件号码（15位或18位数字或字母）');
                                            }
                                            callback();
                                        }
                                    }
                                ]
                            })(<Input placeholder="证件号码" />)
                        ) : (
                            <div className="multiLineText">{formData?.idCard || '--'}</div>
                        )}
                    </Form.Item>
                    <Form.Item label="出生日期">
                        {editStatus ? (
                            getFieldDecorator('birthday', {
                                initialValue:
                                    formData?.birthday !== '' && formData?.birthday
                                        ? moment(formData?.birthday)
                                        : undefined,
                                rules: [{ required: true, message: '出生日期不能为空' }]
                            })(
                                <DatePicker
                                    format="YYYY-MM-DD"
                                    style={{ width: '100%' }}
                                    placeholder="请选择出生日期"
                                />
                            )
                        ) : (
                            <span>
                                {formData?.birthday === '' ? '--' : moment(formData?.birthday).format('YYYY-MM-DD')}
                            </span>
                        )}
                    </Form.Item>
                    <Form.Item label="手机号码">
                        {editStatus ? (
                            getFieldDecorator('mobile', {
                                initialValue: formData.mobile || undefined,
                                rules: [
                                    {
                                        required: true,
                                        validator(rule, value, callback) {
                                            const regex = /^\d{7,11}$/;
                                            if (!value) {
                                                callback('手机号不能为空');
                                            } else if (!regex.test(value)) {
                                                callback('只能输入7-11位数字');
                                            }
                                            callback();
                                        }
                                    }
                                ]
                            })(
                                <Input
                                    placeholder="请填入手机号"
                                    addonBefore={getFieldDecorator('areaCode', {
                                        initialValue: formData.areaCode || '86'
                                    })(
                                        <Select
                                            getPopupContainer={trigger => trigger.parentElement}
                                            placeholder="区号"
                                            style={{ width: 80 }}
                                        >
                                            <Option value="86">+86</Option>
                                            <Option value="65">+65</Option>
                                        </Select>
                                    )}
                                />
                            )
                        ) : (
                            <Text>
                                {formData.mobile
                                    ? `${formData?.areaCode ? `+${formData.areaCode}` : ''} ${formData.mobile}`
                                    : '--'}
                            </Text>
                        )}
                    </Form.Item>
                    <Form.Item label="个人邮箱">
                        {editStatus ? (
                            getFieldDecorator('email', {
                                initialValue: formData?.email,
                                rules: [
                                    {
                                        required: true,
                                        message: '请输入个人邮箱'
                                    },
                                    {
                                        pattern: /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/,
                                        message: '请输入正确的个人邮箱'
                                    },
                                    { max: 100, message: '字数不能超过100个字符' }
                                ]
                            })(<Input placeholder="请输入个人邮箱" allowClear maxLength={100} />)
                        ) : (
                            <div className="multiLineText">{formData?.email || '--'}</div>
                        )}
                    </Form.Item>
                    <Form.Item label="国籍/户籍">
                        {/* eslint-disable-next-line no-nested-ternary */}
                        {editStatus ? (
                            getFieldDecorator('nationalArea', {
                                initialValue: formData?.nationalArea
                                    ? restoreArrayLinkString(formData?.nationalArea)
                                    : [],
                                rules: editStatus ? [{ required: true, message: '请选择国籍/户籍' }] : []
                            })(
                                <CityPicker
                                    valueType="array"
                                    onChange={handleOnHouseHoldChange}
                                    showSearch
                                    placeholder="请选择国籍/户籍"
                                    showOnly={false}
                                />
                            )
                        ) : formData?.nationalArea ? (
                            getFieldDecorator('nationalArea', {
                                initialValue: formData?.nationalArea ? restoreArrayLinkString(formData?.nationalArea)
                                 : []
                            })(
                                <CityPicker
                                    valueType="array"
                                    onChange={handleOnHouseHoldChange}
                                    showSearch
                                    placeholder="请选择国籍/户籍"
                                    showOnly
                            />
                            )
                        ) : (
                            '--'
                        )}
                    </Form.Item>
                    {showHousehold && (
                        <Form.Item label="户籍类型">
                            {editStatus ? (
                                getFieldDecorator('firstHouseholdType', {
                                    initialValue:
                                        firstHouseholdType !== '' && secondHouseholdType !== ''
                                            ? [firstHouseholdType, secondHouseholdType]
                                            : undefined,
                                    rules: [{ required: true, message: '请选择户籍类型' }]
                                })(<Cascader placeholder="请选择户籍类型" options={CENSUS_REGISTER_OPTIONS} />)
                            ) : (
                                <Text>
                                    {CENSUS_REGISTER_OPTIONS?.filter(v => v?.value === firstHouseholdType)[0]?.label ||
                                        '--'}
                                    /
                                    {HOUSEHOLD_TYPE_MAP[firstHouseholdType]?.filter(
                                        v => v?.value === secondHouseholdType
                                    )[0]?.text || '--'}
                                </Text>
                            )}
                        </Form.Item>
                    )}
                    <Form.Item label="居住地址">
                        {getFieldDecorator('address', {
                            initialValue: formData?.address ? restoreArrayLinkString(formData?.address) : []
                        })(
                            <CityPicker
                                style={{ flex: 1 }}
                                valueType="array"
                                showSearch
                                placeholder="请选择居住地址"
                                showOnly={!editStatus}
                            />
                        )}
                        {editStatus
                            ? getFieldDecorator('detailAddress', {
                                  initialValue: formData?.detailAddress || undefined,
                                  rules: [{ max: 200, message: '字数不能超过200个字符' }]
                              })(<Input.TextArea maxLength={200} rows={3} placeholder="请输入详细居住地址" />)
                            : formData?.detailAddress || '--'}
                    </Form.Item>
                    <Form.Item label="最高学历">
                        {/* {editStatus ? (
                            getFieldDecorator('highestDegree', {
                                initialValue: formData?.highestDegree || undefined,
                                rules: [
                                    {
                                        required: true,
                                        message: '最高学历不能为空'
                                    }
                                ]
                            })(
                                <Select placeholder="请选择最高学历">
                                    {agreeTypeList?.map(item => (
                                        <Option value={item.value} key={item.value}>
                                            {item.text}
                                        </Option>
                                    ))}
                                </Select>
                            )
                        ) : (
                            <Text>{getAgreeTypeText(formData?.highestDegree)}</Text>
                        )} */}
                        {formData.eduList.filter(item => item.degree && item.degree !== '8').length
                            ? getAgreeTypeText(
                                  Math.max(
                                      ...formData.eduList
                                          .filter(item => item.degree && item.degree !== '8')
                                          .map(item => Number(item.degree))
                                  ).toString()
                              )
                            : '--'}
                    </Form.Item>
                    <Form.Item label="参加工作时间">
                        {editStatus ? (
                            getFieldDecorator('joinWorkTime', {
                                initialValue:
                                    formData?.joinWorkTime !== '' && formData?.joinWorkTime
                                        ? moment(formData?.joinWorkTime)
                                        : undefined,
                                rules: [{ required: true, message: '请选择参加工作时间' }]
                            })(
                                <DatePicker.MonthPicker
                                    format="YYYY-MM"
                                    style={{ width: '100%' }}
                                    placeholder="请选择参加工作时间"
                                />
                            )
                        ) : (
                            <span>
                                {formData?.joinWorkTime === ''
                                    ? '--'
                                    : moment(formData?.joinWorkTime).format('YYYY-MM')}
                            </span>
                        )}
                    </Form.Item>
                </>
            )}
        </FormContainer>
    );
};

// prop
BasicInfoSection.propTypes = {
    formData: PropTypes.object.isRequired,
    onChange: PropTypes.func.isRequired,
    saveAction: PropTypes.func,
    readonly: PropTypes.bool
};

BasicInfoSection.defaultProps = {
    saveAction: null,
    readonly: false
};

export default BasicInfoSection;
